package ui;

import java.awt.CardLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;

import settings.Settings;

import experiment.Question;

public class QuestionPanel extends JPanel 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5822436625173525898L;
	private Question question;
	private ButtonGroup group;

	public QuestionPanel(Question question)
	{
		this.question = question;
		this.setBorder(new EmptyBorder(new Insets(10,10,10,10)));
		
		BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
		this.setLayout(layout);
		
		JLabel questionLabel = new JLabel("<html><body style='width:"+(Settings.GridWidth-30)+"px'><p>"+this.question.getQuestion()+"");
		this.add(questionLabel);
		

	    group = new ButtonGroup();
	    int id = 0;
		for(Iterator<String> it = this.question.getAnswers().iterator(); it.hasNext();)
		{
			String ans = it.next();
		    JRadioButton button = new JRadioButton(ans);
		    button.setActionCommand(""+id++);
		    group.add(button);
			this.add(button);
		}
		
		group.setSelected((ButtonModel) group.getElements().nextElement().getModel(), true);
		
		JButton confirmButton = new JButton("Ok");
		confirmButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent event) 
			{
				JButton sourceButton = (JButton) event.getSource();
				QuestionPanel questionPanel = ((QuestionPanel)sourceButton.getParent());
				QuestionsPanel questionsPanel = (QuestionsPanel) questionPanel.getParent();
				if(group.getSelection() != null)
				{
					questionsPanel.getExperimentManager().endQuestion(Integer.parseInt(group.getSelection().getActionCommand()));		
					CardLayout layout = ((CardLayout)(questionsPanel.getLayout()));
					layout.next(questionsPanel);
				}
			}
		});
		
		
		this.add(confirmButton);
	}

	
	public Question getQuestion() {
		return question;
	}
	

}
